//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.Provenance.ProvenanceDataService
{
    using System.Text;
    using Microsoft.Research.DataLayer;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Configuration;

    public sealed class DataConnections
    {
        private static ConnectionManager connMgr;
        private static readonly int timeInterval = 0;

        /// <summary>
        /// Initializes the <see cref="DataConnections"/> class.
        /// </summary>
        static DataConnections()
        {
            string retryInterval = ConfigurationManager.AppSettings["RegistryRetryInterval"];
            if (!string.IsNullOrEmpty(retryInterval))
            {
                if (!int.TryParse(retryInterval, out timeInterval))
                {
                    // By Default the timeinterval is set to 5 seconds.
                    timeInterval = 5000;
                }
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataConnections"/> class.
        /// </summary>
        private DataConnections()
        { }

        /// <summary>
        /// Connect and Opens to Registry Connection
        /// </summary>
        /// <returns>Connection</returns>
        public static Connection ConnectRegistry()
        {
            Connection registryConnection = null;
            bool isValid = false;

            do
            {
                try
                {
                    connMgr = ConnectionManager.CreateForAgent(
                        ConnectionManager.CancelBehavior.ThrowException,
                        ConnectionManager.Agent.ExecutionService);

                    registryConnection = connMgr.PickConnection(ConnectionManager.ConnectionUI.NeverShowUI);

                    if (null != registryConnection)
                    {
                        registryConnection.AutoSave = false;

                        //this.poolingConnection =registryConnection.Clone();
                        registryConnection.Open();

                        TridentAuthentication authendicate = new TridentAuthentication(registryConnection);
                        authendicate.AuthenticateUser();

                        isValid = true;
                    }
                }
                catch (Microsoft.Research.DataLayer.ConnectionFailure connectionFailure)
                {
                    TridentErrorHandler.HandleUIException(connectionFailure);
                    isValid = false;
                    System.Threading.Thread.Sleep(timeInterval);
                }
                catch (InvalidOperationException exception)
                {
                    TridentErrorHandler.HandleUIException(exception);
                    isValid = false;
                    System.Threading.Thread.Sleep(timeInterval);
                }
                catch (Exception exception)
                {
                    TridentErrorHandler.HandleUIException(exception);
                    isValid = false;
                    System.Threading.Thread.Sleep(timeInterval);
                }
            } while (!isValid);

            if (null == registryConnection)
            {
                // This will not be hit at all.
                TridentErrorHandler.ThrowTridentCustomException(0, TridentCommonResourceManager.GetString("RegistryNotSelected"));
            }

            return registryConnection;
        }

        /// <summary>
        /// Initializes the registry.
        /// </summary>
        public static void InitializeRegistry()
        {
            // Initialize Connection.
            SR_Connection.Init();
        }

    }
}
